package com.lan.iot;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;
import com.lan.iot.adapter.MyFragmentStateVPAdapter;
import com.lan.iot.entity.SensorEntity;
import com.lan.iot.fragment.VPFdev;
import com.lan.iot.fragment.VPFragment;
import com.lan.iot.fragment.VPFragmentm;
import com.lan.iot.fragment.VPHomeFragment;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.base.Unit;
import com.qweather.sdk.bean.weather.WeatherDailyBean;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.HeConfig;
import com.qweather.sdk.view.QWeather;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;

import cn.com.newland.nle_sdk.requestEntity.SignIn;
import cn.com.newland.nle_sdk.responseEntity.User;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.NCallBack;
import cn.com.newland.nle_sdk.util.NetWorkBusiness;

import static com.lan.iot.Add.DEV_COUNT;

public class Activity_index extends AppCompatActivity {
    List<SensorEntity> sensorEntities;
    static String PREFS_NAME = "user";
    static Map<String, Integer> numMap = new TreeMap<>();
    static Context instance;
    private ViewPager mViewPager; // 主页面来展示子页面 Viewpager
    private BottomNavigationView mBottomNavigationView; //主页面底部tab按钮
    private List<Fragment> mFragmentList; //存储fragment页面，用来作为构造adapter的参数
    private MyFragmentStateVPAdapter mStateVPAdapter;
    double lo = 116.4;
    double la = 39.9;
    String loca = "北京 东城";

    public static void numChange(String key, boolean f) {
        int num = 0;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            num = numMap.getOrDefault(key, 0);
        }
        if (f) {
            ++num;
            numMap.put(key, num);
        } else {
            --num;
            numMap.put(key, num);
        }
    }

    @Override
    protected void onDestroy() {
        SharedPreferences settings = getSharedPreferences(DEV_COUNT, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
//
//        System.out.println(homeFragment.vPfragment1.mAdapter.nData.get(0)); ;
//        Toast.makeText(this,homeFragment.vPfragment1.mAdapter.nData.get(0) , Toast.LENGTH_SHORT).show();
//        editor.putString("devname"+devcount, devname);
//        editor.putString("devtag"+devcount, devtag);
//        editor.putInt("devtype"+devcount, devtype);
//        editor.putInt("roomid"+devcount, roomid);
        int devcount = 0;
        if (homeFragment != null && homeFragment.vPfragment1 != null && homeFragment.vPfragment1.mAdapter != null && homeFragment.vPfragment1.mAdapter.nData != null) {
            int count = homeFragment.vPfragment1.mAdapter.nData.size();
            for (int i = 1; i <= count; i++) {
                devcount++;
                editor.putString("devname" + devcount, homeFragment.vPfragment1.mAdapter.nData.get(i - 1));
                editor.putString("devtag" + devcount, homeFragment.vPfragment1.mAdapter.tagData.get(i - 1));
                editor.putInt("devtype" + devcount, homeFragment.vPfragment1.mAdapter.imgData.get(i - 1));
                editor.putInt("roomid" + devcount, 0);
            }
            count = homeFragment.vPfragment2.mAdapter.nData.size();
            for (int i = 1; i <= count; i++) {
                devcount++;
                editor.putString("devname" + devcount, homeFragment.vPfragment2.mAdapter.nData.get(i - 1));
                editor.putString("devtag" + devcount, homeFragment.vPfragment2.mAdapter.tagData.get(i - 1));
                editor.putInt("devtype" + devcount, homeFragment.vPfragment2.mAdapter.imgData.get(i - 1));
                editor.putInt("roomid" + devcount, 1);
            }
            count = homeFragment.vPfragment3.mAdapter.nData.size();
            for (int i = 1; i <= count; i++) {
                devcount++;
                editor.putString("devname" + devcount, homeFragment.vPfragment3.mAdapter.nData.get(i - 1));
                editor.putString("devtag" + devcount, homeFragment.vPfragment3.mAdapter.tagData.get(i - 1));
                editor.putInt("devtype" + devcount, homeFragment.vPfragment3.mAdapter.imgData.get(i - 1));
                editor.putInt("roomid" + devcount, 2);
            }
            editor.putInt("devcount", devcount);
            editor.commit();
        }
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            Window window = getWindow();

            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS

                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            window.setStatusBarColor(Color.TRANSPARENT);

            window.setNavigationBarColor(Color.TRANSPARENT);
        }
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_index);
        instance = this;
//        wetherInfo wein = new GPSUtils().getProvince();

//        getLocation();
//        String loca_d = lo + "," + la;
//        System.out.println(loca_d);
//        System.out.println(loca);
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String username = settings.getString("f", "");
        if (username.equals("")) {
            Intent intent = new Intent();
            intent.setClass(Activity_index.this, Login.class);
            startActivity(intent);
            finish();
        }
//        sensorEntities=MainActivity1.gainDevices();
//        sa();
        init();
        initeView();
        initData();
//        initWeather(loca_d);
        mBottomNavigationView.setItemIconTintList(null);
        //获取底部导航图标颜色，根据图标颜色设置文字颜色
        Resources resource = getResources();
        @SuppressLint("ResourceType")
        ColorStateList csl = resource.getColorStateList(R.drawable.bottom_btn_selected_color);

        mBottomNavigationView.setItemTextColor(csl);

        setFListener();
        setBListener();
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmService.class);
        pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_MUTABLE);
        Intent intent2 = new Intent(this, AlarmService_2.class);
        pendingIntent2 = PendingIntent.getService(this, 0, intent2, PendingIntent.FLAG_MUTABLE);
        Intent intent3 = new Intent(this, AlarmService_3.class);
        pendingIntent3 = PendingIntent.getService(this, 0, intent3, PendingIntent.FLAG_MUTABLE);
        Intent intent4 = new Intent(this, AlarmService_4.class);
        pendingIntent4 = PendingIntent.getService(this, 0, intent4, PendingIntent.FLAG_MUTABLE);
        ontime();
//        startAlarmRepeatEveryDay(20,44,AlarmService.class);
//        startAlarmRepeatEveryDay(23,56,AlarmService_2.class);
//        startAlarmRepeatEveryDay(7,5,AlarmService_3.class);
//        startAlarmRepeatEveryDay(21,32,AlarmService_4.class);
//        Intent intent=new Intent();
//        intent.setClass(this,AlarmService.class);
//        startService(intent);
    }

    static AlarmManager alarmManager;
    static PendingIntent pendingIntent;
    static PendingIntent pendingIntent2;
    static PendingIntent pendingIntent3;
    static PendingIntent pendingIntent4;

    public static void offtime() {
        alarmManager.cancel(pendingIntent);
        alarmManager.cancel(pendingIntent2);
        alarmManager.cancel(pendingIntent3);
        alarmManager.cancel(pendingIntent4);
    }

    public static void ontime() {
        System.out.println("8888888888888888");
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP
                , getlong(20,00), AlarmManager.INTERVAL_DAY, pendingIntent);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP
                , getlong(23,56), AlarmManager.INTERVAL_DAY, pendingIntent2);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP
                , getlong(7,5), AlarmManager.INTERVAL_DAY, pendingIntent3);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP
                , getlong(21,32), AlarmManager.INTERVAL_DAY, pendingIntent4);
    }
public static long getlong(int hour,int min){
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    //这里时区需要设置一下，不然会有8个小时的时间差
    calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    //设置每天为13：50点提醒
    calendar.set(Calendar.MINUTE, min);
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    long firstTime = SystemClock.elapsedRealtime();
    long systemTime = System.currentTimeMillis();
    long selectTime = calendar.getTimeInMillis();
    //当前时间大于设置时间，说明今天提醒时间已经过去了，设置为明天的点来提醒
    if (systemTime > selectTime) {
        System.out.println(hour+" "+min+"888666");
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        selectTime = calendar.getTimeInMillis();
    }else         System.out.println(hour+" "+min+"999");

    long time = selectTime - systemTime;// 计算现在时间到设定时间的时间差
   long  triggerTime = firstTime + time;//系统当前的时间+时间差
    return triggerTime;
}
    public void startAlarmRepeatEveryDay(int hour, int min, Class inclass) {
        Log.i("", "startAlarmRepeatEveryDay");
        Intent intent = new Intent(this, inclass);
//        intent.setAction("com.alarm.notice");

        pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_MUTABLE);

        //设置提醒时间

        //13：50点提醒，实现方式1

        //13：50点提醒，实现方式2
//        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, selectTime,AlarmManager.INTERVAL_DAY, pendingIntent);
    }


    String token;
    static NetWorkBusiness netWorkBusiness;

    private void init() {

        NetWorkBusiness netWorkBusiness2 = new NetWorkBusiness("", "http://www.nlecloud.com/");
        netWorkBusiness2.signIn(new SignIn("17680316790", "1234567890"), new NCallBack<BaseResponseEntity<User>>(getApplicationContext()) {
            @Override
            protected void onResponse(BaseResponseEntity<User> response) {
                netWorkBusiness = new NetWorkBusiness(response.getResultObj().getAccessToken(), "http://www.nlecloud.com/");
                token = response.getResultObj().getAccessToken();
            }
        });
    }

    private void sa() {
        Intent intent = new Intent();
        intent.setClass(Activity_index.this, light.class);
        startActivity(intent);
    }

    //反向处理，按钮设置点击事件，按钮关联页面
    private void setBListener() {
        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.menu_home:
                        mViewPager.setCurrentItem(0);
                        break;
                    case R.id.menu_recommend:
                        mViewPager.setCurrentItem(1);
                        break;
                    case R.id.menu_mine:
                        mViewPager.setCurrentItem(2);
                        break;
                }
                return true;
            }
        });
    }

    private void setFListener() {
        mStateVPAdapter = new MyFragmentStateVPAdapter(getSupportFragmentManager(), mFragmentList);
        mViewPager.setAdapter(mStateVPAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                onPagerSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void onPagerSelected(int position) {
        switch (position) {
            case 0:
                mBottomNavigationView.setSelectedItemId(R.id.menu_home);
                break;
            case 1:
                mBottomNavigationView.setSelectedItemId(R.id.menu_recommend);
                break;
            case 2:
                mBottomNavigationView.setSelectedItemId(R.id.menu_mine);
                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    VPFdev recommendFragment;
    VPHomeFragment homeFragment;

    private void initData() {
        mFragmentList = new ArrayList<>();
        homeFragment = VPHomeFragment.newInstance("家", R.drawable.ji1, Activity_index.this);
        recommendFragment = new VPFdev().newInstance("设备", R.drawable.ji5);
        VPFragmentm mineFragment = new VPFragmentm().newInstance("我", R.drawable.ji6);

        //添加页面
        mFragmentList.add(homeFragment);
        mFragmentList.add(recommendFragment);
        mFragmentList.add(mineFragment);
    }

    public void control(final String deviceID, final String tag, final String val) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                netWorkBusiness.control(deviceID, tag, val, new NCallBack<BaseResponseEntity>(getApplicationContext()) {
                    @Override
                    protected void onResponse(BaseResponseEntity response) {
                        if (response.getStatus() != 0) return;//请求失败

                    }
                });
            }
        }).start();
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Fragment fragmentFirst = getSupportFragmentManager().findFragmentByTag(makeFragmentName(mViewPager.getId(), 0));
        if (fragmentFirst != null) {
            homeFragment = (VPHomeFragment) fragmentFirst;
        }
        System.out.println("666");
        Fragment fragmentSecond = getSupportFragmentManager().findFragmentByTag(makeFragmentName(mViewPager.getId(), 1));
        if (fragmentSecond != null) {
            recommendFragment = (VPFdev) fragmentSecond;
        }
    }

    /**
     * 参考fragmentPagerAdapter中的寻找fragment的方法
     */
    private static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }

    private void initeView() {
        mViewPager = findViewById(R.id.vp);
        mViewPager.setOffscreenPageLimit(3);
        mBottomNavigationView = findViewById(R.id.bottom_nav_menu);
    }
}